#include <stdio.h>
#include <stdlib.h> 
#include <unistd.h>  
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> 
#include <termios.h>
#include <errno.h>   
#include <limits.h> 
#include <asm/ioctls.h>
#include <time.h>


//#define DEBUG                 0



static int openSerial(int port)
{
    int fd;

    struct termios opt; 
    char serial_name[15];

    sprintf(serial_name, "/dev/ttyTX%d", port);
    printf("open serila name:%s \n", serial_name);
    fd = open(serial_name, O_RDWR | O_NOCTTY);                        
    if(fd < 0) {
        perror(serial_name);
        return -1;
    }

    tcgetattr(fd, &opt);      

    cfsetispeed(&opt, B57600);
    cfsetospeed(&opt, B57600);
    
    /*
     * raw mode
     */
    opt.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
    opt.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
    opt.c_oflag &= ~(OPOST);
    opt.c_cflag &= ~(CSIZE | PARENB);
    opt.c_cflag |= CS8;

    /*
     * 'DATA_LEN' bytes can be read by serial
     */
    opt.c_cc[VMIN]   =   30;                                      
    opt.c_cc[VTIME]  =   5;

    if (tcsetattr(fd, TCSANOW, &opt)<0) {
        return -1;
    }

    return fd;
}


int main(void)
{
    int fd1, fd2,i;
    char string1[30] ={0x2,0x1,0xa,0x2,0x0,0x0,0x0,0x34,0x0,0x55,0x0,0x0,0x0,0x71,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0};
    char string2[] = {0x01,0x0a,0x3,0x4,0x5,0x6};
    char  buff[30]={0};

    fd1 = openSerial(1);                                               /* open /dev/ttyTX1             */
//    fd2 = openSerial(2);                                               /* open /dev/ttyTX2             */
   
    while(1) {
		//printf("enter a word:");
		//scanf("%s",string1);
        write(fd1, string2, 6); 
        sleep(1);
        read(fd1,  buff,  6);
        //printf("%s\n",buff);
        for(i=0;i<6;i++)
        {
			if(string2[i]==buff[i])
			printf("good ");
			else
			printf("bad ");
        //printf("%X ", buff[i]);
		}
        printf("\n");
        //sleep(1);

        //write(fd1, string2, strlen(string2)); 
        //read(fd2,  buff,  strlen(string2));
        //printf("%s\n", buff);
        sleep(1);
        //printf("\n");
    }

    return 0;
}

/*********************************************************************************************************
    end file
*********************************************************************************************************/
